from flask import render_template,Blueprint,request
from sqlalchemy.sql.functions import user
from apps.util.LayData import LayData
from apps.pojo.Entity import User ,UserSchema,db

user_bp = Blueprint('user', __name__,url_prefix='/user')
user_schema = UserSchema(many=True)
@user_bp.route('/tolist')
def tolist():
    return render_template('user/list.html')



@user_bp.route('/list',methods=['GET','POST'])
def list():
    #接受分页参数  page:当前页，limit:1当前显示的条数
    page = request.args.get('page',1,type=int)
    limit = request.args.get('limit',10,type=int)

    #查询用户数
    count = User.query.count()

    #查询用户集合数据
    offset = (page-1)*limit
    userlist = User.query.offset(offset).limit(limit).all()
    #将集合转为JSON
    users = user_schema.dump(userlist)
    #构造Latui格式对象
    return {
        "code":0,
        "msg":"查询成功",
        "count":count,
        "data":users
    }
@user_bp.route('/toadd')
def toadd():
    return render_template('user/add.html')

@user_bp.route('/addSave',methods=['POST'])
def addSave():
    param = request.form
    user = User()
    user.username = param.get('username')
    user.password = param.get('password')
    user.sex = param.get('sex')
    try:
        #保存用户到数据库
         db.session.add(user)
        #提交事务
         db.session.commit()
        #返回json数据
         return LayData.data2(200,'添加成功')
    except Exception as e:
        #回滚事务
        db.session.rollback()
        return LayData.data2(500,'添加失败')



@user_bp.route('/toupdate')
def toupdate(id):
    user = User.query.filter(User.id==id).first()
    return render_template('user/edit.html',user=user)


@user_bp.route('/updateSave')
def toupdateSave():
    param = request.form
    id = param.get('id')
    user = User.query.filter(User.id==id).first()
    user.username = param.get('username')
    user.password = param.get('password')
    user.sex = param.get('sex')
    try:
        db.session.commit()
        return LayData.data2(200,'修改成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500,'修改失败')
    return render_template('user/edit.html',user=user)
